package com.fzb.forum4j.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.fzb.forum4j.controller.api.ICommonsAction;
import com.fzb.forum4j.po.CommonArea;
import com.fzb.forum4j.po.QueryMode;
import com.fzb.forum4j.po.User;
import com.fzb.forum4j.service.api.IBaseService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class CommonsAction<T> extends ActionSupport implements ICommonsAction<T>,ModelDriven<Object>,Preparable,ServletRequestAware{

	/**
	 * 实现了基本的增删改查的Action
	 */
	
	public Logger log = Logger.getLogger(getClass());
	
	private static final long serialVersionUID = 7697501969580031239L;
	private T t;
	private QueryMode<T> qmd;
	private static String diskUploadPath;
	private static String homePage;
	
	@Resource(name="baseServiceImpl")
	private IBaseService<Object> service;
	
	private HttpServletRequest request;
	
	@Override
	public String add(){
		qmd.setId((Integer) getService().addEntity(t));
		return "add_success";
		
	}
	@SuppressWarnings("unchecked")
	@Override
	public String del(){
		if (qmd.getIds()!=null) {
			getService().batchDelByIds((QueryMode<Object>) qmd);
		}
		else{
			getService().reMoveEntity(t);
		}
		return null;
	}
	
	public String modify(){
		getService().modifyEntity(t);
		return null;
	}
	public String edit(){
		return modify();
	}
	@Override
	public String getMsgsByEid() {
		return null;
	}
	
	@Override
	public void prepare() throws Exception {
		this.qmd=new QueryMode<T>();
		this.t=getClazz().newInstance();
	}

	@Override
	public Object getModel() {
		getQmd().setT(getT());
		return getQmd();
	}
 
	public QueryMode<T> getQmd() {
		return qmd;
	}

	public void setQmd(QueryMode<T> qmd) {
		this.qmd = qmd;
	}

	public T getT() {
		return t;
	}

	public Map<String,Object> getData(){
		if(qmd!=null){
			return qmd.getData();
		}
		return null;
	}
	public void setT(T t) {
		this.t = t;
	}
 
	private Map<String,Object> getSession(){
		return ActionContext.getContext().getSession();
	}
	
	protected Object getObjFromSessionByAttr(String name){
		return ActionContext.getContext().getSession().get(name);
	}
	
	public void setAttrToSession(String name,Object obj){
		getSession().put(name, obj);
	}
	public void setAttrToRequest(String name,Object obj){
		request.setAttribute(name, obj);
	}

	/**得到 session 中的user
	 * @return
	 */
	protected User getUserMsg() {
		return (User) getSession().get("userMsg");
	}

	public IBaseService<Object> getService() {
		return service;
	}

	public void setService(IBaseService<Object> service) {
		this.service = service;
	}
	
	@SuppressWarnings("unchecked")
	public String list(){
		service.getList((QueryMode<Object>) qmd);
		return "list";
	}
	

	public String go_edit(){
		return "edit";
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}
	public HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	@SuppressWarnings("unchecked")
	protected Map<String,String> getWebSite() {
		return (Map<String, String>) ActionContext.getContext().getApplication().get("webSite");
	}
	protected String getContextPath() {
		return  getRequest().getContextPath()+"/";
	}
 
	/**上传文件用
	 * @param file
	 * @param path(从upload为基础的路径)
	 * @param fileName(文件名)
	 * @return
	 */
	public static boolean copyFile(File file,String path,String fileName){
		try {
			FileUtils.copyFile(file, new File(diskUploadPath+path+"/"+fileName));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**初始化当前环境的路径
	 * @param diskUploadPath
	 */
	public static void initDiskUploadPath(String diskUploadPath) {
		CommonsAction.diskUploadPath = diskUploadPath;
	}
	
	private String dir;
	
	/**
	 * 文章,blog中文件上传
	 * @return
	 */
	public String uploadFile(){
		String fileName=((CommonArea)getT()).getImgFileFileName();
		fileName=new Date().getTime()+fileName.substring(fileName.lastIndexOf("."), fileName.length());
			Boolean uploadStatus=copyFile(((CommonArea)getT()).getImgFile(), dir,fileName);
			if (uploadStatus) {
				getQmd().getData().put("url", getHomePage()+"upload/"+dir+"/"+fileName);
				getQmd().getData().put("error", 0);
			} else {
				getQmd().getData().put("error", 1);
				getQmd().getData().put("message", "错误");
			}
		
		return "json";
	}

	
	/**得到当前项目的主页，用于邮箱中连接地址需要
	 * @return
	 */
	protected static String getHomePage(){
		if(homePage==null){
			homePage=ServletActionContext.getRequest().getScheme().toString()+"://" + ServletActionContext.getRequest().getHeader("host")+ ServletActionContext.getRequest().getContextPath()+"/";
		
		}
		return homePage;
	}
	
	public void setDir(String dir) {
		this.dir = dir;
	}
	
	/**通过反射得到泛型的具体类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Class<T> getClazz() {
		return (Class<T>) ((ParameterizedType)getClass()
				.getGenericSuperclass())
				.getActualTypeArguments()[0];
	}
	@Override
	public String update() {
		return modify();
	}
}
